@file:Suppress("unused")

package com.hjh.tool.util

import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.IOException
import java.io.InputStreamReader
import kotlin.jvm.Throws
import kotlin.text.toIntOrNull
import kotlin.text.trim

object GpioUtil {

    @Throws(IOException::class)
    fun chmod(instruct: String) {
        val runtime = Runtime.getRuntime()
        val process = runtime.exec("su")
        val dataOutputStream = DataOutputStream(process.outputStream)
        dataOutputStream.writeBytes(instruct)
        dataOutputStream.flush()
        dataOutputStream.close()
        process.waitFor()
    }

    @Throws(IOException::class)
    fun exportGpio(gpioNumber: Int) {
        chmod("echo $gpioNumber > /sys/class/gpio/export")
    }

    @Throws(IOException::class)
    fun setGpioDirection(gpioNumber: Int, direction: String) {
        chmod("echo $direction > /sys/class/gpio/gpio$gpioNumber/direction")
    }

    @Throws(IOException::class)
    fun setGpioValue(gpioNumber: Int, value: Int) {
        chmod("echo $value > /sys/class/gpio/gpio$gpioNumber/value")
    }

    @Throws(IOException::class)
    fun initGpio(gpioNumber: Int, direction: String) {
        exportGpio(gpioNumber)
        setGpioDirection(gpioNumber, direction)
    }

    /**
     * 读取GPIO状态
     * @return GPIO状态字符串，读取失败返回null
     */
    @Throws(IOException::class)
    fun readGpioState(gpioNumber: Int): String? {
        val runtime = Runtime.getRuntime()
        val process = runtime.exec("su")
        val outputStream = DataOutputStream(process.outputStream)
        val inputStream = process.inputStream
        val reader = BufferedReader(InputStreamReader(inputStream))

        outputStream.writeBytes("cat /sys/class/fise_gpio$gpioNumber/fise_gpio${gpioNumber}_state\n")
        outputStream.writeBytes("exit\n")
        outputStream.flush()

        val result = reader.readLine()

        outputStream.close()
        reader.close()
        process.waitFor()

        return result
    }

    /**
     * 读取标准GPIO值
     * @param gpioNumber GPIO编号
     * @return GPIO值(0或1)，读取失败返回null
     */
    @Throws(IOException::class)
    fun readGpioValue(gpioNumber: Int): Int? {
        val runtime = Runtime.getRuntime()
        val process = runtime.exec("su")
        val outputStream = DataOutputStream(process.outputStream)
        val inputStream = process.inputStream
        val reader = BufferedReader(InputStreamReader(inputStream))

        outputStream.writeBytes("cat /sys/class/gpio/gpio$gpioNumber/value\n")
        outputStream.writeBytes("exit\n")
        outputStream.flush()

        val result = reader.readLine()?.trim()?.toIntOrNull()

        outputStream.close()
        reader.close()
        process.waitFor()

        return result
    }
}